# -*- coding: utf-8 -*-
"""
 Created by wq.wang on 2017/12/21
"""
import logging

from wserver.base.exception import WException
from wserver.base.wapi import WApi

_logger = logging.getLogger(__name__)

SERVICE = {}
PRE_URLS = set()

RESTFUL_METHOD = ("get", 'post', 'put', 'delete')


class ServiceManager(type):
    """
    服务定义
    """

    def __new__(cls, name, bases, attrs):
        super_new = super(ServiceManager, cls).__new__
        if "_abstract" in attrs:
            _abstract = attrs.pop("_abstract")
            if _abstract:
                return super_new(cls, name, bases, attrs)

        # 注册api
        if name in SERVICE:
            msg = "重复定义服务%s" % name
            # _logger.error(msg)
            raise WException(msg)
        wapis = {}
        pre_url = attrs.get("pre_url", name).strip("/")
        pre_url = '/' + pre_url.lower()
        if pre_url in PRE_URLS:
            raise WException("重复使用相同pre_url:%s" % pre_url)
        PRE_URLS.add(pre_url)
        attrs['pre_url'] = pre_url
        for k, v in attrs.items():
            if isinstance(v, WApi):
                wapis.update({v.url or k: v})
                path = pre_url if k in RESTFUL_METHOD else "%s/%s" % (pre_url, v.url or k)
                v.set_service(path=path, tags=[name], operationId="%s_%s" % (name, k))

        attrs.update({"_wapis": wapis})
        service = super_new(cls, name, bases, attrs)
        SERVICE.update({name: service})
        return service


class Service(metaclass=ServiceManager):
    """
    基础服务
    """
    _abstract = True

    def __init__(self, *args, **kwargs):
        pass

    @classmethod
    def handle(cls, api, *args, **kwargs):
        raise NotImplementedError("%s没有实现对处理功能" % (cls.__name__))

    @classmethod
    def gen_route(cls):
        raise NotImplementedError("%s没有实现对路由功能" % (cls.__name__))
